package com.ruoyi.reception;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.receipt.domain.TbKnowledgeList;
import com.ruoyi.receipt.domain.TbKnowledgeManager;
import com.ruoyi.receipt.domain.TbKnowledgePlan;
import com.ruoyi.receipt.domain.TbUser;
import com.ruoyi.receipt.service.ITbKnowledgeListService;
import com.ruoyi.receipt.service.ITbKnowledgeManagerService;
import com.ruoyi.receipt.service.ITbKnowledgePlanService;
import com.ruoyi.receipt.service.ITbUserService;
import com.ruoyi.receipt.service.impl.TbUserServiceImpl;
import com.ruoyi.receipt.utils.CurrentUserUtils;
import jdk.nashorn.internal.ir.LiteralNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 知识点管理Controller
 * 
 * @author ruoyi
 * @date 2021-03-29
 */
@RestController
@RequestMapping("/reception/knowledgeRecManagerRec")
public class TbKnowledgeManagerRecController extends BaseController
{
    @Autowired
    private ITbKnowledgeManagerService tbKnowledgeManagerService;

    @Autowired
    private ITbKnowledgePlanService tbKnowledgePlanService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private ITbUserService tbUserService;

    @Autowired
    private ITbKnowledgeListService iTbKnowledgeListService;
    /**
     * 开始学习播放接口
     * @return
     */
    @RequestMapping("/startLearningPlay")
    public AjaxResult startLearningPlay(@RequestBody Map map){
        //这里获取所有的和用户年级对应的知识点信息 进行随机抽取 保证每次抽取的知识点都不相同
        //随机抽取一个目录去查询知识点信息
        TbKnowledgeList tbKnowledgeList = new TbKnowledgeList();
        TbKnowledgeManager tbKnowledgeManager = new TbKnowledgeManager();
        startPage(map,tbKnowledgeManager);
        tbKnowledgeManager.setIsDel(0);
        //查询到所有年级和登录用户相同的知识点
        List<TbKnowledgeManager> list = tbKnowledgeManagerService.selectTbKnowledgeManagerListRec(tbKnowledgeManager);
        //所有的有和登录用户年级匹配的知识点目录集合
        Set<Long> knowledgeSet = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            knowledgeSet.add(list.get(i).getKnowledgeListId());
        }
        List<TbKnowledgeManager> tbKnowledgeManagers = new ArrayList<>();
        //从筛选的目录集合中随机返回一个知识点目录编号
        if (knowledgeSet.size() > 0){
            Long randomElement = getRandomElement(knowledgeSet);
            //根据目录编号去筛选符合年级和登录用户相同的知识点
            tbKnowledgeManager.setKnowledgeListId(randomElement);
            startPage(map,tbKnowledgeManager);
            //分页查询该知识点目录下面的知识点
            tbKnowledgeManagers = tbKnowledgeManagerService.selectTbKnowledgeManagerListRec(tbKnowledgeManager);
        }
        //从筛选的知识点目录集合中随机抽取一个目录下的知识点集合返回
        //打乱集合排序
        Map resultMap = new HashMap();
        if (tbKnowledgeManagers.size() > 0){
            TableDataInfo tbKnowledgeManagerList = getDataTable(tbKnowledgeManagers);
            //放入知识点分页列表信息
            resultMap.put("tbKnowledgeManagerList",tbKnowledgeManagerList);
            //获取到第一个知识点的详情信息
            TbKnowledgeManager knowledgeManager = (TbKnowledgeManager) tbKnowledgeManagerList.getRows().get(0);
            //放入第一个知识点的视频信息
            resultMap.put("vedioUrl",knowledgeManager.getVideoUrl());
            //根据知识点编号去查询教案信息
            TbKnowledgePlan plan = tbKnowledgePlanService.getPlanByManagerId(knowledgeManager.getId());
            //放入教案信息
            resultMap.put("teachContent",plan.getContent());
        }
        return AjaxResult.success(resultMap);
    }

    /**
     * 例题解析 传入知识点编号
     * @param map
     * @return
     */
    @RequestMapping("/analysisExamples")
    public AjaxResult analysisExamples(@RequestBody Map map){
        //根据知识点编号获取该知识点对应的目录
        long knowledgeManagerRelated = 0l;
        if (StringUtils.isNotNull(map.get("knowledgeManagerRelated"))){
            knowledgeManagerRelated = Long.parseLong(map.get("knowledgeManagerRelated").toString());
        }
        TbKnowledgeManager tbKnowledgeManager = tbKnowledgeManagerService.selectTbKnowledgeManagerById(knowledgeManagerRelated);
        //根据目录编号去筛选符合年级和登录用户相同的知识点
        tbKnowledgeManager.setKnowledgeListId(tbKnowledgeManager.getKnowledgeListId());
        tbKnowledgeManager.setIsDel(0);
        startPage(map,tbKnowledgeManager);
        //分页查询该知识点目录下面的知识点
        List<TbKnowledgeManager> tbKnowledgeManagers = tbKnowledgeManagerService.selectTbKnowledgeManagerListRec(tbKnowledgeManager);
        Map resultMap = new HashMap();
        if (tbKnowledgeManagers.size() > 0){
            TableDataInfo tbKnowledgeManagerList = getDataTable(tbKnowledgeManagers);
            //放入知识点分页列表信息
            resultMap.put("tbKnowledgeManagerList",tbKnowledgeManagerList);
            //获取到第一个知识点的详情信息
            TbKnowledgeManager knowledgeManager = (TbKnowledgeManager) tbKnowledgeManagerList.getRows().get(0);
            //放入第一个知识点的视频信息
            resultMap.put("vedioUrl",knowledgeManager.getVideoUrl());
            //根据知识点编号去查询教案信息
            TbKnowledgePlan plan = tbKnowledgePlanService.getPlanByManagerId(knowledgeManager.getId());
            //放入教案信息
            resultMap.put("teachContent",plan.getContent());
        }
        return AjaxResult.success(resultMap);
    }

    /**
     * 从set中随机取得一个元素
     * @param set
     * @return
     */
    public static <E> E getRandomElement(Set<E> set){
        int rn = getRandomInt(set.size());
        int i = 0;
        for (E e : set) {
            if(i==rn){
                return e;
            }
            i++;
        }
        return null;
    }

    /**
     * 获得一个[0,max)之间的随机整数。
     * @param max
     * @return
     */
    public static int getRandomInt(int max) {
        return getRandom().nextInt(max);
    }

    //双重校验锁获取一个Random单例
    public static ThreadLocalRandom getRandom() {
        return ThreadLocalRandom.current();
		/*if(random==null){
			synchronized (RandomUtils.class) {
				if(random==null){
					random =new Random();
				}
			}
		}

		return random;*/
    }

    /**
     * 查询知识点管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(@RequestBody Map map)
    {
        TbKnowledgeManager tbKnowledgeManager = new TbKnowledgeManager();
        startPage(map,tbKnowledgeManager);
        List<TbKnowledgeManager> list = tbKnowledgeManagerService.selectTbKnowledgeManagerListRec(tbKnowledgeManager);
        return getDataTable(list);
    }

    //处理分页数据
    private void startPage(Map map,TbKnowledgeManager tbKnowledgeManager) {
        //获取当前登录用户
        TbUser currentUser = CurrentUserUtils.getCurrentUser();
        if (StringUtils.isNull(currentUser.getGrade())){
            currentUser = tbUserService.selectTbUserById(currentUser.getId());
        }
        tbKnowledgeManager.setGrade(currentUser.getGrade());
        //处理分页数据
        PageDomain pageDomain = TableSupport.buildPageRequest();
        //如果不传分页信息 默认查询第一页  每页显示10行
        Integer pageNum = 0;
        Integer pageSize = 0;
        if (StringUtils.isNull(map.get("pageNum"))){
            pageNum = 1;
        }else {
            pageNum = Integer.valueOf(map.get("pageNum").toString());
        }
        if (StringUtils.isNull(map.get("pageSize"))){
            pageSize = 10;
        }else {
            pageSize = Integer.valueOf(map.get("pageSize").toString());
        }
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 导出知识点管理列表
     */
    @Log(title = "导出知识点管理列表", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TbKnowledgeManager tbKnowledgeManager)
    {
        List<TbKnowledgeManager> list = tbKnowledgeManagerService.selectTbKnowledgeManagerList(tbKnowledgeManager);
        ExcelUtil<TbKnowledgeManager> util = new ExcelUtil<TbKnowledgeManager>(TbKnowledgeManager.class);
        return util.exportExcel(list, "manager");
    }

    /**
     * 导出知识点审核列表
     */
    @Log(title = "导出知识点审核列表", businessType = BusinessType.EXPORT)
    @GetMapping("/exportAudit")
    public AjaxResult exportAudit(TbKnowledgeManager tbKnowledgeManager)
    {
        List<TbKnowledgeManager> list = tbKnowledgeManagerService.selectTbKnowledgeManagerList(tbKnowledgeManager);
        ExcelUtil<TbKnowledgeManager> util = new ExcelUtil<TbKnowledgeManager>(TbKnowledgeManager.class);
        return util.exportExcel(list, "manager");
    }

    /**
     * 获取知识点管理详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        //这里根据知识点编号去查询教案信息
        TbKnowledgePlan plan = tbKnowledgePlanService.getPlanByManagerId(id.longValue());
        TbKnowledgeManager tbKnowledgeManager = tbKnowledgeManagerService.selectTbKnowledgeManagerById(id);
        tbKnowledgeManager.setTeachingPlanContent(plan.getContent());
        return AjaxResult.success(tbKnowledgeManager);
    }

    /**
     * 新增知识点管理
     */
    @Log(title = "新增知识点", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody TbKnowledgeManager tbKnowledgeManager)
    {
        TbKnowledgePlan tbKnowledgePlan = new TbKnowledgePlan();
        tbKnowledgeManager.setId(idWorker.nextId());
        //这里保存一条知识点信息 一条知识点教案
        tbKnowledgePlan.setContent(tbKnowledgeManager.getTeachingPlanContent());
        tbKnowledgePlan.setKnowledgeManagerId(tbKnowledgeManager.getId());
        tbKnowledgePlan.setId(idWorker.nextId());
        tbKnowledgePlanService.insertTbKnowledgePlan(tbKnowledgePlan);
        return toAjax(tbKnowledgeManagerService.insertTbKnowledgeManager(tbKnowledgeManager));
    }

    /**
     * 修改知识点管理
     */
    @Log(title = "修改知识点", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody TbKnowledgeManager tbKnowledgeManager)
    {
        //修改知识点教案内容
        Map<String,Object> map = new HashMap<>();
        map.put("manageId",tbKnowledgeManager.getId());
        map.put("content",tbKnowledgeManager.getTeachingPlanContent());
        tbKnowledgePlanService.updateTbKnowledgePlanContent(map);
        return toAjax(tbKnowledgeManagerService.updateTbKnowledgeManager(tbKnowledgeManager));
    }

    /**
     * 删除知识点管理
     */
    @Log(title = "删除知识点", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tbKnowledgeManagerService.deleteTbKnowledgeManagerByIds(ids));
    }

    /**
     * 逻辑删除知识点
     */
    @Log(title = "逻辑删除知识点", businessType = BusinessType.DELETE)
    @DeleteMapping("/delManagerLogic/{ids}")
    public AjaxResult delManagerLogic(@PathVariable Long[] ids)
    {
        return toAjax(tbKnowledgeManagerService.delManagerLogic(ids));
    }


    @GetMapping("/listName/{name}")
    public List<TbKnowledgeManager> listName(@PathVariable String name){
        List<TbKnowledgeManager> tbKnowledgeManagers = tbKnowledgeManagerService.selectKmName(name);
        return tbKnowledgeManagers;
    }

    /**
     * 查询审核知识点
     * @param tbKnowledgeManager
     * @return
     */
    @GetMapping("/selectKnowledge")
    public TableDataInfo selectKnowledge(TbKnowledgeManager tbKnowledgeManager){
        startPage();
        List<TbKnowledgeManager> tbKnowledgeManagers = tbKnowledgeManagerService.selectKonwledgeStatus(tbKnowledgeManager);
        return getDataTable(tbKnowledgeManagers);
    }
}
